package com.fengchao.util.common;

import com.fengchao.api.config.Constant;
import main.java.com.UpYun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

/**
 * Created by wangnian on 2016/6/12.
 */
@Component
public class UpyunTools {

    //文档地址:https://github.com/upyun/java-sdk
    @Autowired
    private Environment env;
    private static Logger logger = LoggerFactory.getLogger(UpyunTools.class);

    /**
     * 根据文件名切割成 后缀名
     *
     * @param fileName
     * @return
     */
    public String suffix(String fileName) {
        try {
            String suffix = fileName.substring(fileName.lastIndexOf('.'));
            return suffix;
        } catch (Exception ex) {
            logger.warn("后缀名错误 fileName:{} ex:{} ", fileName, ex);
        }
        return "";
    }

    /**
     * 上传file对象
     *
     * @param fileName
     * @param bytes
     * @return
     */
    public String upload(String fileName, byte[] bytes) {
        UpYun upyun = new UpYun(env.getProperty("upyum.bucketName"), env.getProperty("upyum.userName"), env.getProperty("upyum.password"));
        upyun.setApiDomain(UpYun.ED_AUTO);//选择最优的接入点
        try {
            boolean boole = upyun.writeFile(fileName, bytes, true);
            if (boole) {
                String urlLocation = env.getProperty("upyum.location") + fileName;
                logger.info("上传文件成功;fileName:{} urlLocation:{}", fileName, urlLocation);
                return urlLocation;
            } else {
                logger.error("上传文件不成功");
            }
        } catch (Exception ex) {
            logger.error("上传文件异常:ex:{}", ex);
        }
        return null;
    }

    public String upload(String fileName, String base64Str) {
        try {
            String imgBase64 = base64Str.substring(base64Str.indexOf(",") + 1);
            byte[] bytes = new BASE64Decoder().decodeBuffer(imgBase64);
            String location = upload(Constant.CONFIGMAP.get("usr.user_icon") + fileName, bytes);
            return location;
        } catch (Exception ex) {
            logger.error("base64Str上传头像异常:{}", ex);
        }
        return "";
    }

}


